package com.zzptc.syl.viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //将ViewPager实例化
        ViewPager2 pv=findViewById(R.id.vp);
        //创建碎片的集合
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new OneFragment());
        fragments.add(new TwoFragment());
        fragments.add(new ThreeFragment());
        //for循环将一个页面实现多次循环
//        for (int i = 0; i < 3; i++) {
//            //将碎片添加在集合中
//            oneFragments.add(new OneFragment());
//        }
        //创建适配器（导入两个必要参数：getSupportFragmentManager+getLifecycle）
        FragmentStateAdapter adapter = new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @Override
            public int getItemCount() {
                //集合的长度
                return fragments.size();
            }
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                //数据源的实例
                return fragments.get(position);
            }
        };
        //将ViewPager（数据源）放入适配器
        pv.setAdapter(adapter);
    }
}